import { parseTime } from './admin'
import { getColumnData, getDictData } from '@/api/custom/formDesigner'
import XLSX from '@/utils/xlsx.core.min.js'
import { getAllListData } from "@/api/custom/formPoster";

/**
 * 表格时间格式化
 */
export function formatDate(cellValue) {
  if (cellValue == null || cellValue == "") return "";
  var date = new Date(cellValue)
  var year = date.getFullYear()
  var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xDC00 && code <= 0xDFFF) i--
  }
  return s
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

// /**
//  * This is just a simple version of deep copy
//  * Has a lot of edge cases bug
//  * If you want to use a perfect deep copy, use lodash's _.cloneDeep
//  * @param {Object} source
//  * @returns {Object}
//  */
// export function deepClone(source) {
//   if (!source && typeof source !== 'object') {
//     throw new Error('error arguments', 'deepClone')
//   }
//   const targetObj = source.constructor === Array ? [] : {}
//   Object.keys(source).forEach(keys => {
//     if (source[keys] && typeof source[keys] === 'object') {
//       targetObj[keys] = deepClone(source[keys])
//     } else {
//       targetObj[keys] = source[keys]
//     }
//   })
//   return targetObj
// }

// 深拷贝对象
// add by awesome https://github.com/JakHuang/form-generator/blob/dev/src/utils/index.js#L107
export function deepClone(obj) {
  const _toString = Object.prototype.toString

  // null, undefined, non-object, function
  if (!obj || typeof obj !== 'object') {
    return obj
  }

  // DOM Node
  if (obj.nodeType && 'cloneNode' in obj) {
    return obj.cloneNode(true)
  }

  // Date
  if (_toString.call(obj) === '[object Date]') {
    return new Date(obj.getTime())
  }

  // RegExp
  if (_toString.call(obj) === '[object RegExp]') {
    const flags = []
    if (obj.global) { flags.push('g') }
    if (obj.multiline) { flags.push('m') }
    if (obj.ignoreCase) { flags.push('i') }

    return new RegExp(obj.source, flags.join(''))
  }

  const result = Array.isArray(obj) ? [] : obj.constructor ? new obj.constructor() : {}

  for (const key in obj) {
    result[key] = deepClone(obj[key])
  }

  return result
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + ''
  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  return (+(randomNum + timestamp)).toString(32)
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

export function makeMap(str, expectsLowerCase) {
  const map = Object.create(null)
  const list = str.split(',')
  for (let i = 0; i < list.length; i++) {
    map[list[i]] = true
  }
  return expectsLowerCase
    ? val => map[val.toLowerCase()]
    : val => map[val]
}

export const exportDefault = 'export default '

export const beautifierConf = {
  html: {
    indent_size: '2',
    indent_char: ' ',
    max_preserve_newlines: '-1',
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: 'separate',
    brace_style: 'end-expand',
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: false,
    end_with_newline: true,
    wrap_line_length: '110',
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true
  },
  js: {
    indent_size: '2',
    indent_char: ' ',
    max_preserve_newlines: '-1',
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: 'normal',
    brace_style: 'end-expand',
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: true,
    end_with_newline: true,
    wrap_line_length: '110',
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true
  }
}

// 首字母大小
export function titleCase(str) {
  return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
}

// 下划转驼峰
export function camelCase(str) {
  return str.replace(/_[a-z]/g, str1 => str1.substr(-1).toUpperCase())
}

export function isNumberStr(str) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
}

// -转驼峰
export function toCamelCase(str, upperCaseFirst) {
  str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
    return group1.toUpperCase();
  });

  if (upperCaseFirst && str) {
    str = str.charAt(0).toUpperCase() + str.slice(1);
  }

  return str;
}

/**
 * excel数据导出
 *
 * fields : {
 *      name: 'field101',
 *      desc: '单行文本'
 * }
 *
 * tagIcons: [
 *      {
 *          tag: tag,
            dataType: item.dataType,
            option: []
 *      }
 * ]
 *
 * name: ''  导出时excel的名称（默认使用 表单名称 或者 子表单标签）
 *
 * tableValue: 子表单数据 [{ 'field101': '110' }]
*/
export function exportToExcel (fields, tagIcons, excelName, tableValue) {
    let cols = []
    let header = {
        // id: '序号'
    }
    fields.forEach((key) => {
        header[key.name] = key.desc
    })
    // header['create_time'] = '创建时间'
    const specialTypes = ['switch', 'cascader', 'select', 'radio', 'checkbox','tree-table']; //需处理后在table中展示
    let exceldata = tableValue.map((item, serial) => {
        let data = {
        // 'id': serial + 1
        }
        cols.push({
            wch: 30
        })
        fields.map((key, index) => {
            let value = item[key.name]
            let tag = tagIcons[index].tag
            if (specialTypes.includes(tag)) {
                value = getShowValue(value, tag, tagIcons[index].dataType, tagIcons[index].option)
            } else if (key.format === 'datetime') {
                value = getDateTime(value)
            } else if (key.tag === 'upload') {
                value = getFileNames(value)
            }
            data[key.name] = value
            cols.push({
                wch: 30
            })
        })
        // data['create_time'] = getDateTime(item.create_time)
        cols.push({
            wch: 30
        })
        return data
    })
    // 新建空workbook，然后加入worksheet
    const ws = XLSX.utils.json_to_sheet([header, ...exceldata], {
        skipHeader: true
    })
    // 设置每列的列宽，10代表10个字符，注意中文占2个字符
    ws['!cols'] = cols
    // 新建book
    const wb = XLSX.utils.book_new()
    // 生成xlsx文件(book,sheet数据,sheet命名)
    XLSX.utils.book_append_sheet(wb, ws, excelName)
    // 写文件(book,xlsx文件名称)
    XLSX.writeFile(wb, `${excelName}.xlsx`)
}

//特殊类型组件数据展示
function getShowValue(data, tag, dataType, options) {
    if (!data) {
      return ''
    } //空数据
    if (tag === 'switch') {
      return data === options[0].toString() ? '是' : (data === options[1].toString() ? '否' : '')
    } else if (tag === 'checkbox' || tag === 'select' || tag === 'radio') {
      if (dataType === 'static') {
        let keys = (data + '').split(',')
        if (keys.length > 1 && (tag === 'select' || tag === 'radio')) {
          return ''
        } else {
          let str = []
          options.length > 0 && keys.map((res, index) => {
            options.forEach((item) => {
              if (item.value.toString() === res) {
                str.push(item.label)
                return true
              }
            })
          })
          return str.join(',')
        }
      } else {
        return data
      }
    } else if (tag === 'cascader' || tag === 'tree-table') {
      let keys = (data + '').split(',')
      if (dataType === 'dynamic') {
        return keys.join('/')
      } else if (dataType === 'static') {
        let str = []
        let index = 0
        keys.length > 0 && getLabelByKey(options, keys, index, str)
        return str.join('/')
      } else if (dataType === 'region') {
        let str = []
        let index = 0
        keys.length > 0 && getLabelByKey(regionData, keys, index, str)
        return str.join('/')
      }

    }
  }

//根据key值获取label
function getLabelByKey(options, key, index, str) {
    options.length > 0 && options.forEach((item) => {
        if (item.value.toString() === key[index]) {
            str.push(item.label)
            index++
            index < key.length && getLabelByKey(item.children, key, index, str)
            return true
        }
    })
}

//获取所有字段的tag、dataType、option
async function getTagIcons(data, tagIcons) {
    if (data.length === 0) return
    let comps = data.filter((item) => {
      return item.__config__.tag !== 'TitleLine'
    })
    for (let i = 0; i < comps.length; i++) {
      let item = comps[i]
      if (item.__config__.tag === 'el-card' || item.__config__.tag === 'el-tabs' || item.__config__.tag === 'Steps'|| item.__config__.tag === 'el-collapse') {
        let tem = item.__config__.children.map((c) => {
          getTagIcons(c.__config__.children)
        })
      } else {
        let tag = item.__config__.tagIcon
        let options = []
        if (tag === 'switch') {
          options = [item['active-value'], item['inactive-value']]
          tagIcons.push({
            tag: tag,
            dataType: item.dataType,
            option: [...options]
          })
        } else if (['select', 'radio', 'checkbox'].includes(tag)) {
          if (item.dataType === 'static') {
            options = item.options
            tagIcons.push({
              tag: tag,
              dataType: item.dataType,
              option: [...options]
            })
          } else if (item.dataType === 'dictionary' && item.dictName !== '') {
            let res = await getDictData({
              dictType: item.dictName
            })
            if (res.code === 0) {
              res.data.forEach((item) => {
                options.push({
                  label: item.label,
                  value: item.label
                })
              })
            }
            tagIcons.push({
              tag: tag,
              dataType: item.dataType,
              option: [...options]
            })
          } else if (item.dataType === 'datasource' && item.tableName !== '' && item.fieldName !== '') {
            let res = await getColumnData({
              tableName: item.tableName,
              column: item.fieldName,
            })
            if (res.code === 0) {
              res.data.forEach((item) => {
                options.push({
                  label: item,
                  value: item
                })
              })
            }
            tagIcons.push({
              tag: tag,
              dataType: item.dataType,
              option: [...options]
            })

          }
        } else if (tag === 'cascader'|| tag === 'tree-table') {
          if (item.dataType === 'dynamic') {
            await getDynamicOptions(item.fields,item.formName).then(res => {
              options = res
            })
            tagIcons.push({
              tag: tag,
              dataType: item.dataType,
              option: [...options]
            })
          } else if (item.dataType === 'static'){
            options = item.options
            tagIcons.push({
              tag: tag,
              dataType: item.dataType,
              option: [...options]
            })
          } else if (item.dataType === 'region') {
            tagIcons.push({
              tag: tag,
              dataType: item.dataType,
              option: regionData
            })
          }
        } else {
          tagIcons.push({
            tag: tag,
            dataType: item.dataType,
            option: [...options]
          })
        }
      }
    }
    return tagIcons;
  }
//获取级联动态选项
async function getDynamicOptions(fields,formName) {
    let params = {
        tableName: formName,
        dataType: '2'
    }
    let res = await getAllListData(params)
    let options = []
    if (res.code === 0) {
    let tableData = res.data
    if (fields.length > 0) {
    for (let i = 0; i < fields[0].datas.length; i++) {
        let opt = fields[0].datas[i]
        let values = await getColumnData({
        tableName: formName,
        column: opt.fieldName,
        })
        values.data.map((item) => {
        let node = {
            label: item,
            value: item
        }
        let child = getChildren(opt.fieldName, item, 1,fields,tableData)
        if (child.length > 0) {
            node.children = child
        }
        options.push(node)
        })
    }
        }
        }
    return options
}
//获取子级选项
function getChildren(name, data, index,fields,tableData) {
    let option = []
    if (index >= fields.length) {
        return option
    } else {
        fields[index].datas.map((item) => {
        if (item.parent === name) {
            [...new Set(tableData.filter((field) => {
            return field[name] === data
            }).map((field)=>{return field[item.fieldName]}))].map((field) => {
            let node = {
                label: field,
                value: field
            }
            let child = getChildren(item.fieldName, field, index+1,fields,tableData)
            if (child.length > 0) {
                node.children = child
            }
            option.push(node)
            })
        }
        })
        return option
    }
}
//上传组件获取文件名
function getFileNames(data) {
    if (!data) {
        return ''
    } //空数据
    if (!isJson(data)) {
        return ''
    }
    let files = JSON.parse(data)
    return files.map((item) => {
        return item.name
    }).toString()
}

// 时间戳转日期时间
function getDateTime(time) {
  if (!time) return ''
  let date = new Date(time)
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  let hour = date.getHours()
  let minute = date.getMinutes()
  let second = date.getSeconds()
  return `${year}-${month<10?'0':''}${month}-${day<10?'0':''}${day} ${hour<10?'0':''}${hour}:${minute<10?'0':''}${minute}:${second<10?'0':''}${second}`
}

//判断是否是json
function isJson(str) {
    if (typeof (str) === 'string') {
      try {
        var obj = JSON.parse(str)
        if (typeof (obj) === 'object' && obj) {
          return true
        } else {
          return false
        }
      } catch (e) {
        return false
      }
    }
}

export function download(url,name){
    const link = document.createElement('a');
    // 这里是将链接地址url转成blob地址，
    fetch(url).then(res => res.blob()).then(blob => {
        link.href = URL.createObjectURL(blob)
        // 下载文件的名称及文件类型后缀
        link.download = name;
        document.body.appendChild(link)
        link.click()
        //在资源下载完成后 清除 占用的缓存资源
        window.URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
    });
}

export function reorganizationParam(obj) {
    const clone = {}
    for (const i in obj) {
        if (obj[i] !== '' && obj[i] !== undefined && obj[i] !== null) {
        clone[i] = obj[i]
        }
    }
    return clone
}

// 制造10位随机数(字符串)
export function makeRandom () {
    return (Math.random() * 1000000000000000 + '').substring(0, 10)
}
